<template>
  <HeadContainer class="mine-settings-mail-verify" :title="$t('title.mailVerify')" @back="back">
    <div v-if="inputEmail">
      <div class="mb-4 d-flex flex-column">
        <InputWrap
          v-model="form.mail.value"
          :label="$t('label.yourMail')"
          :sub-label="isVerify"
          :sub-label-status="verifyStatus"
          :placeholder="$t('placeholder.email')"
          :typing-append="true"
          :append-icon="showClose"
          :err-msg="form.mail.error"
          :disabled="changeVerifiedMail"
          trim
          @click:append-icon="onAppendIconClick"
        ></InputWrap>
      </div>
      <div
        v-if="changeVerifiedMail"
        @click="onChangeVerifiedMail"
        class="primary-btn w-100 d-flex justify-center align-center mt-6"
      >
        {{ $t('info.changeOtherMail') }}
      </div>
      <div
        v-if="!changeVerifiedMail"
        @click="onMailVerify"
        :class="['primary-btn', { 'primary-btn-disable': isVerifying }]"
        class="w-100 d-flex justify-center align-center mt-6"
      >
        {{
          isVerifying
            ? `${countdown}s ${$t('info.countdownGetCode')}`
            : verifyStatus
            ? $t('info.changeOtherMail')
            : $t('title.mailVerify')
        }}
      </div>
      <div
        v-if="isVerifying"
        @click="toInputCode"
        class="font-size-14 font-weight-400 line-height-120 text-center py-5 pointer"
      >
        {{ $t('info.backInputCode') }}
      </div>
      <p v-if="mailVerifyError" class="font-size-14 font-weight-400 line-height-120 text-primary-x pt-1 text-end">
        {{ mailVerifyError }}
      </p>
    </div>
    <div v-if="confirmVerify">
      <InputVerificationCode v-model="form.code.value" :err-msg="form.code.error" />
      <div class="text-center font-size-12 font-weight-400 line-height-120 pt-4">
        {{ $t('info.verifyCodeTo') }} {{ form.mail.value }}
      </div>
      <div v-if="!isVerifying" class="text-center font-size-14 font-weight-500 line-height-120 pt-4">
        <span @click="sendAgain" class="text-primary pointer">{{ $t('info.sendAgain') }}</span> {{ $t('info.or') }}
        <span @click="changeMail" class="text-primary pointer">{{ $t('info.changeMail') }}</span>
      </div>
      <div v-if="isVerifying" class="text-center font-size-14 font-weight-500 line-height-120 pt-4">
        <span class="text-primary">{{ countdown }}s</span> {{ $t('info.countdownGetCode') }}
      </div>
      <div @click="onConfirmVerify" class="primary-btn w-100 d-flex justify-center align-center mt-6">
        {{ $t('info.confirmVerify') }}
      </div>
      <p v-if="confirmVerifyError" class="font-size-14 font-weight-400 line-height-120 text-primary-x pt-1 text-end">
        {{ confirmVerifyError }}
      </p>
    </div>
  </HeadContainer>
</template>
<script setup>
import { computed, watch, watchEffect } from 'vue'
import { useRouter } from 'vue-router'
import { onKeyStroke } from '@vueuse/core'
import { storeToRefs } from 'pinia'
import { useAccountStore } from '@/store/account'
import { useMailVerifyStore } from '@/store/mail-verify'
import { usePopupMessageStore } from '@/store/popup-message'
import { $t } from '@/i18n'
import { validate } from '@/plugins/yup'
import InputVerificationCode from '@/components/form/InputVerificationCode.vue'
import InputWrap from '@/components/form/InputWrap.vue'
import HeadContainer from '@/components/layout/HeadContainer.vue'
import { useMailVerify } from '@/compositions/mine/mailVerify'
import { SEND_EMAIL_CODE_TYPE } from '@/constant'

const router = useRouter()
const accountStore = useAccountStore()
const { userData } = storeToRefs(accountStore)
const { isVerifying, countdown } = storeToRefs(useMailVerifyStore())
const { open } = usePopupMessageStore()
const emits = defineEmits(['toPage'])
const {
  sendMailVerificationCode,
  validateEmail,
  resetForm,
  resetError,
  form,
  mailVerifyError,
  confirmVerifyError,
  verifyStatus,
  inputEmail,
  changeVerifiedMail,
  confirmVerify,
} = useMailVerify()

function back() {
  if (!verifyStatus.value && inputEmail.value) {
    form.mail.value = userData.value.email
    form.code.value = ''
    resetForm('mail', 'code')
    backToStart()
    resetError()
  } else if (!verifyStatus.value && confirmVerify.value) {
    inputEmail.value = true
    confirmVerify.value = false
    verifyStatus.value = false
  } else if (verifyStatus.value && inputEmail.value && !changeVerifiedMail.value && !isVerifying.value) {
    changeVerifiedMail.value = true
    form.mail.value = userData.value.email
    resetForm('mail')
    resetError()
  } else if (verifyStatus.value && confirmVerify.value) {
    confirmVerify.value = false
    inputEmail.value = true
  } else {
    form.code.value = ''
    emits('toPage', 2, 'settings')
    resetForm('mail', 'code')
    resetError()
  }
}
function backToStart() {
  if (
    (!verifyStatus.value && inputEmail.value) ||
    (verifyStatus.value && inputEmail.value && !changeVerifiedMail.value)
  ) {
    if (!window.history.state.back || window.history.state.back.includes('mail-verify')) {
      emits('toPage', 2, 'settings')
    } else {
      router.push({
        path: window.history.state.back,
      })
    }
  }
}
const toInputCode = () => {
  inputEmail.value = false
  confirmVerify.value = true
}

const isVerify = computed(() =>
  verifyStatus.value && !changeVerifiedMail.value
    ? null
    : verifyStatus.value
    ? $t('subLabel.verified')
    : $t('subLabel.unverified'),
)
watch(userData, (newValue) => {
  verifyStatus.value = newValue.is_bind_email
})

const showClose = computed(() => {
  return changeVerifiedMail.value ? null : 'close'
})

// 清除輸入匡
const onAppendIconClick = () => (form.mail.value = '')

// 信箱驗證(寄送驗證碼至信箱)
const onMailVerify = async () => {
  await validate(form.mail.schema, form.mail)
  console.log(`驗證的信箱為: ${form.mail.value}`)
  if (form.mail.check) {
    !verifyStatus.value
      ? sendMailVerificationCode(SEND_EMAIL_CODE_TYPE.BIND)
      : sendMailVerificationCode(SEND_EMAIL_CODE_TYPE.CHANGE)
  } else {
    open($t('yup.string.email'))
  }
  resetError()
}

// 已通過驗證的信箱，要更換其他信箱
const onChangeVerifiedMail = async () => {
  changeVerifiedMail.value = false
  form.mail.value = ''
  console.log('你的信箱', userData.value.email)
}

// 再寄一次驗證碼至信箱
const sendAgain = () => {
  form.code.value = ''
  resetForm('code')
  resetError()

  !verifyStatus.value
    ? sendMailVerificationCode(SEND_EMAIL_CODE_TYPE.BIND)
    : sendMailVerificationCode(SEND_EMAIL_CODE_TYPE.CHANGE)
}

// 更換信箱
const changeMail = () => {
  inputEmail.value = true
  confirmVerify.value = false
  form.code.value = ''
  resetForm('code')
  resetError()
}

// 驗證信箱給的號碼
const onConfirmVerify = async () => {
  console.log(`驗證六位碼: ${form.code.value}`)
  await validate(form.code.schema, form.code)
  if (form.code.check) {
    form.code.error = ''
    if (!verifyStatus.value) {
      validateEmail(SEND_EMAIL_CODE_TYPE.BIND)
      userData.value.is_bind_email = true
    } else {
      validateEmail(SEND_EMAIL_CODE_TYPE.CHANGE)
    }
  } else {
    open($t('yup.mixed.default'))
  }
}

watchEffect(() => {
  onKeyStroke('Enter', inputEmail.value ? onMailVerify : onConfirmVerify)
})
</script>
